package studiodiva.portfolio.client.view.particleengine;

import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.canvas.dom.client.CssColor;

import java.util.List;

import static studiodiva.portfolio.client.lib.lang.Lang.list;
import static studiodiva.portfolio.client.lib.lang.Lang.schedule;

import studiodiva.portfolio.client.lib.lang.Lang.Work;
import studiodiva.portfolio.client.lib.lang.Run;
import studiodiva.portfolio.client.lib.view.View;

public class CanvasDisplay extends View<Canvas> implements Run {
  private static final int REFRESH_RATE = 25;
  private Context2d buffer2D;
  private final Canvas canvas = Canvas.createIfSupported();
  private Context2d canvas2D;
  private final Canvas canvasBuffer = Canvas.createIfSupported();
  private final List<Object2D> objects = list();
  private final CssColor redrawColor = CssColor.make("rgba(255,255,255,0.3)");
  private final Work work = schedule(REFRESH_RATE, this);

  public CanvasDisplay() {
    initWidget(canvas);
  }

  public void add(Object2D object) {
    objects.add(object);
  }

  public void hide() {
    setVisible(false);
    work.stop();
  }

  public void run() {
    buffer2D.setFillStyle(redrawColor);
    buffer2D.fillRect(0, 0, getWidth(), getHeight());
    for (Object2D object : objects) {
      object.update();
      object.draw(buffer2D);
    }
    canvas2D.drawImage(buffer2D.getCanvas(), 0, 0);
  }

  @Override
  public void setSize(int width, int height) {
    super.setSize(width, height);
    canvas.setCoordinateSpaceWidth(width);
    canvas.setCoordinateSpaceHeight(height);
    canvasBuffer.setCoordinateSpaceWidth(width);
    canvasBuffer.setCoordinateSpaceHeight(height);
    canvas2D = canvas.getContext2d();
    buffer2D = canvasBuffer.getContext2d();
  }

  public void show() {
    setVisible(true);
    work.start();
  }
}
